package com.diit.analysisitest;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @所属包名称 :	com.diit.diitydzf.utils
 * @描述 :    存储工具类
 * @作者 :	wh
 * @COPYRIGHT :	copyright(c) 2016,Rights Reserved
 * @版本 :	v1.0
 * @创建日期 :	2016/5/7
 */
public class StorageUtil {
    /**
     * 是否存在外置sd卡（通用，包含5.0以上系统）
     *
     * @param mContext
     * @return
     */
    public static boolean isSDCardEnable(Context mContext) {
        boolean isMounted = false;
        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        try {
            Method getVolumList = StorageManager.class.getMethod("getVolumeList");
            getVolumList.setAccessible(true);
            Object[] results = (Object[]) getVolumList.invoke(sm);
            if (results != null) {
                for (Object result : results) {
                    Method mRemoveable = result.getClass().getMethod("isRemovable");
                    Boolean isRemovable = (Boolean) mRemoveable.invoke(result);
                    if (isRemovable) {
                        Method getPath = result.getClass().getMethod("getPath");
                        String path = (String) getPath.invoke(result);
                        Method getState = sm.getClass().getMethod("getVolumeState", String.class);
                        String state = (String) getState.invoke(sm, path);
                        if (state.equals(Environment.MEDIA_MOUNTED)) {
                            isMounted = true;
                            break;
                        }
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return isMounted;
    }

    /**
     * 获取外置SD卡根路径
     *
     * @param context
     * @return
     */
    public static String getSDCardRootPath(Context context) {
        return getStoragePath(context, true);
    }

    /**
     * 获取sd卡空余空间
     *
     * @param sdpath
     * @return
     */
    public static long getSDCardFreeSize(String sdpath) {
        return getStorageFreeSize(sdpath);
    }

    /**
     * 获取sd卡全部空间
     *
     * @param sdpath
     * @return
     */
    public static long getSDCardAllSize(String sdpath) {
        return getStorageAllSize(sdpath);
    }

    /**
     * 获取内部存储根路径
     *
     * @param context
     * @return
     */
    public static String getROMRootPath(Context context) {
        return getStoragePath(context, false);
    }

    /**
     * 获取内部存储空余空间
     *
     * @param rompath
     * @return
     */
    public static long getROMFreeSize(String rompath) {
        return getStorageFreeSize(rompath);
    }

    /**
     * 获取内部存储全部空间
     *
     * @param rompath
     * @return
     */
    public static long getROMAllSize(String rompath) {
        return getStorageAllSize(rompath);
    }

    /**
     * 通过反射调用获取内置存储和外置sd卡根路径(通用)
     *
     * @param mContext    上下文
     * @param is_removale 是否可移除，false返回内部存储，true返回外置sd卡
     * @return
     */
    private static String getStoragePath(Context mContext, boolean is_removale) {

        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (is_removale == removable) {
                    return path;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取存储的剩余空间（单位M）
     *
     * @param sdpath
     * @return
     */
    private static long getStorageFreeSize(String sdpath) {
        //取得SD卡文件路径
        File path = new File(sdpath);
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        return (freeBlocks * blockSize) / 1024 / 1024; //单位MB
    }

    /**
     * 获取存储的全部空间（单位M）
     *
     * @param sdpath
     * @return
     */
    private static long getStorageAllSize(String sdpath) {
        //取得SD卡文件路径
        File path = new File(sdpath);
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //获取所有数据块数
        long allBlocks = sf.getBlockCount();
        return (allBlocks * blockSize) / 1024 / 1024; //单位MB
    }
}
